//
//  NSString+STString.m
//  ShaBaoOnline
//
//  Created by huang yong on 16/7/11.
//  Copyright © 2016年 com.ShaBaoOnline.www. All rights reserved.
//

#import "NSString+STString.h"
#import <CommonCrypto/CommonCrypto.h>

@implementation NSString (STString)
    //得到前一天
+ (NSString *)cutOutLastFourStr:(NSString *)cardStr WithNum:(NSInteger)num {
    NSString *returnStr= nil;
    returnStr =  [cardStr substringFromIndex:cardStr.length- num ];
    return returnStr;
}
    
+ (NSString *)getYesterdaywithStr:(NSString *)bill_timeStr {
    NSString *str = nil;
    NSString *timeStr = [self getToday];
    NSString *subStr = [timeStr substringToIndex:[timeStr length] - 2];
    NSString *baseStr = @"220000";
    if (bill_timeStr.length == 1) {
        bill_timeStr = [NSString stringWithFormat:@"0%@",bill_timeStr];
    }
    NSString *newStr = [NSString stringWithFormat:@"%@%@%@",subStr,bill_timeStr,baseStr];
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyyMMddHHmmss"];
    [df setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"] ];
    NSDate*date =[[NSDate alloc]init];
    date =[df dateFromString:newStr];
    str = [NSString stringWithFormat:@"%@",date];
    NSDate *lastDay = [NSDate dateWithTimeInterval:-24*60*60 sinceDate:date];//前一天
    NSDate *nextDay = [NSDate dateWithTimeInterval:24*60*60 sinceDate:date];//后一天
    NSDateFormatter *format=[[NSDateFormatter alloc] init];
    NSTimeZone* timeZone = [NSTimeZone timeZoneWithName:@"zh_CN"];
    [format setTimeZone:timeZone];
    [format setDateFormat:@"yyyyMMddHHmmss"];
    NSString* ruturnStr = [format stringFromDate:lastDay];
    NSLog(@"re= %@",ruturnStr);
    NSRange range = NSMakeRange(6,2);
    NSString *endStr = [ruturnStr substringWithRange:range];
    return endStr;
}
    
- (NSString *)timeString {
    NSString* string = [self substringToIndex:14];
    NSLog(@"%@",string);
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
    NSString *tstr = [outputFormatter stringFromDate:inputDate];
    return tstr;
}

- (NSString *)productReviewstimeString {
    NSString* string = [self substringToIndex:14];
    NSLog(@"%@",string);
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:@"yyyy.MM.dd"];
    NSString *tstr = [outputFormatter stringFromDate:inputDate];
    return tstr;
}
- (NSString *)timeIntervalString {
    NSString* string = [self substringToIndex:14];
    NSLog(@"%@",string);
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSString *tstr = [outputFormatter stringFromDate:inputDate];
    return tstr;
}

- (NSString *)timeSaveMoneyString {
    //    NSString *str = nil;
    NSLog(@"%@",self);
    
    NSString* string = [self substringToIndex:14];
    NSLog(@"%@",string);
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *tstr = [outputFormatter stringFromDate:inputDate];
    return tstr;
}

- (NSString *)timeMyMessageString {
    //    NSString *str = nil;
    NSString* string = [self substringToIndex:14];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = [inputFormatter dateFromString:string];
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
    [outputFormatter setLocale:[NSLocale currentLocale]];
//    [outputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
     [outputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *tstr = [outputFormatter stringFromDate:inputDate];
    return tstr;
}

- (NSString *)timeMycommunityStoreString {
    //    NSString *str = nil;
    NSString* string = [self substringToIndex:10];
    NSString *todaystr = PXY_STR(@"%@000",string);
    NSDate* date = [NSDate dateWithTimeIntervalSince1970:[string doubleValue]];
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
    NSDate* inputDate = date;
    NSDateFormatter *outputFormatter = [[NSDateFormatter alloc] init] ;
    [outputFormatter setLocale:[NSLocale currentLocale]];
    //[outputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
    [outputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *tstr = [outputFormatter stringFromDate:inputDate];
    return tstr;
}

//时间转年龄
- (NSInteger)ageWithDateOfBirth:(NSString *)birthDate
{
    // 出生日期转换 年月日
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyyMMdd"];
    NSDate* inputDate = [inputFormatter dateFromString:self];
    NSDateComponents *components1 = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:inputDate];
    NSInteger brithDateYear  = [components1 year];
    NSInteger brithDateDay   = [components1 day];
    NSInteger brithDateMonth = [components1 month];
    
    // 获取系统当前 年月日
    NSDateComponents *components2 = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];
    NSInteger currentDateYear  = [components2 year];
    NSInteger currentDateDay   = [components2 day];
    NSInteger currentDateMonth = [components2 month];
    
    // 计算年龄
    NSInteger iAge = currentDateYear - brithDateYear - 1;
    if ((currentDateMonth > brithDateMonth) || (currentDateMonth == brithDateMonth && currentDateDay >= brithDateDay)) {
        iAge++;
    }
    
    return iAge;
}

+(NSString *)stringTOjson:(id)temps   //把字典和数组转换成json字符串
    {
        NSData* jsonData =[NSJSONSerialization dataWithJSONObject:temps
                                                          options:NSJSONWritingPrettyPrinted error:nil];
        NSString *strs=[[NSString alloc] initWithData:jsonData
                                             encoding:NSUTF8StringEncoding];
        return strs;
}
+ (NSString *)getIntervalToday {
    NSDate* today = [NSDate date];
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyyMMddHHmmss"];
    NSString* s1 = [df stringFromDate:today];
    NSDate* date = [df dateFromString:s1];
    //转换时间格式
    NSDateFormatter*df2 = [[NSDateFormatter alloc]init];//格式化
    [df2 setDateFormat:@"yyyyMMddHHmmss"];
    [df2 setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    NSString *todayStr = [df2 stringFromDate:date];
    return todayStr;
}
+(NSString *)timeInterval:(NSString *)lasttime {
    NSString *string = @"";
    NSString *orderTime = [lasttime timeIntervalString];
    // NSString *timeStr = [NSString distanceTimeWithBeforeTime:[orderTime doubleValue]];
    NSString *timeStr = [NSString timeIntervalFromLastTime:orderTime lastTimeFormat:@"yyyyMMddHHmmss" ToCurrentTime:[NSString getIntervalToday] currentTimeFormat:@"yyyyMMddHHmmss"];
    string = timeStr;
    return string;
};
//------------------------------------------计算上次日期距离现在多久-----------------
/**
 *  计算上次日期距离现在多久
 *
 *  @param lastTime    上次日期(需要和格式对应)
 *  @param format1     上次日期格式
 *  @param currentTime 最近日期(需要和格式对应)
 *  @param format2     最近日期格式
 *
 *  @return xx分钟前、xx小时前、xx天前
 */
+ (NSString *)timeIntervalFromLastTime:(NSString *)lastTime
                        lastTimeFormat:(NSString *)format1
                         ToCurrentTime:(NSString *)currentTime
                     currentTimeFormat:(NSString *)format2{
    //上次时间
    NSDateFormatter *dateFormatter1 = [[NSDateFormatter alloc]init];
    dateFormatter1.dateFormat = format1;
    NSDate *lastDate = [dateFormatter1 dateFromString:lastTime];
    //当前时间
    NSDateFormatter *dateFormatter2 = [[NSDateFormatter alloc]init];
    dateFormatter2.dateFormat = format2;
    NSDate *currentDate = [dateFormatter2 dateFromString:currentTime];
    return [self timeIntervalFromLastTime:lastDate ToCurrentTime:currentDate];
}

+ (NSString *)timeIntervalFromLastTime:(NSDate *)lastTime ToCurrentTime:(NSDate *)currentTime{
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    //上次时间
    NSDate *lastDate = [lastTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:lastTime]];
    //当前时间
    NSDate *currentDate = [currentTime dateByAddingTimeInterval:[timeZone secondsFromGMTForDate:currentTime]];
    //时间间隔
    NSInteger intevalTime = [currentDate timeIntervalSinceReferenceDate] - [lastDate timeIntervalSinceReferenceDate];
    
    //秒、分、小时、天、月、年
    NSInteger minutes = intevalTime / 60;
    NSInteger hours = intevalTime / 60 / 60;
    NSInteger day = intevalTime / 60 / 60 / 24;
    NSInteger month = intevalTime / 60 / 60 / 24 / 30;
    NSInteger yers = intevalTime / 60 / 60 / 24 / 365;
    
    if (minutes <= 10) {
        return  @"刚刚";
    }else if (minutes < 60){
        return [NSString stringWithFormat: @"%ld分钟前",(long)minutes];
    }else if (hours < 24){
        return [NSString stringWithFormat: @"%ld小时前",(long)hours];
    }else if (day < 30){
        return [NSString stringWithFormat: @"%ld天前",(long)day];
    }else if (month < 12){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"M月d日";
        NSString * time = [df stringFromDate:lastDate];
        return time;
    }else if (yers >= 1){
        NSDateFormatter * df =[[NSDateFormatter alloc]init];
        df.dateFormat = @"yyyy年M月d日";
        NSString * time = [df stringFromDate:lastDate];
        return time;
    }
    return @"";
}



+ (NSString *)getToday {
    NSDate* today = [NSDate date];
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyy-MM-dd"];
    NSString* s1 = [df stringFromDate:today];
    NSLog(@" s1s1s1s%@",s1);
    NSDate* date = [df dateFromString:s1];
    //转换时间格式
    NSDateFormatter*df2 = [[NSDateFormatter alloc]init];//格式化
    [df2 setDateFormat:@"yyyy-MM-dd"];
    [df2 setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    NSLog(@"%@",[df2 stringFromDate:date]);
    NSString *todayStr = [df2 stringFromDate:date];
    return todayStr;
}

+ (NSString *)getTodaySS {
    NSDate* today = [NSDate date];
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyyMMddHHmmssSSS"];
    NSString* s1 = [df stringFromDate:today];
    NSLog(@" s1s1s1s%@",s1);
    NSDate* date = [df dateFromString:s1];
    //转换时间格式
    NSDateFormatter*df2 = [[NSDateFormatter alloc]init];//格式化
    [df2 setDateFormat:@"yyyyMMddHHmmssSSS"];
    [df2 setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    NSLog(@"%@",[df2 stringFromDate:date]);
    NSString *todayStr = [df2 stringFromDate:date];
    return todayStr;
}

+ (NSString *)getdataString:(NSDate *) date11 {
    NSDate* today = date11;
    NSDateFormatter*df = [[NSDateFormatter alloc]init];//格式化
    [df setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString* s1 = [df stringFromDate:today];
    NSLog(@" s1s1s1s%@",s1);
    NSDate* date = [df dateFromString:s1];
    //转换时间格式
    NSDateFormatter*df2 = [[NSDateFormatter alloc]init];//格式化
    [df2 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    [df2 setLocale:[[NSLocale alloc]initWithLocaleIdentifier:@"zh_CN"]];
    NSLog(@"%@",[df2 stringFromDate:date]);
    NSString *todayStr = [df2 stringFromDate:date];
    return todayStr;
}
// 判断是否是整型
    
+ (BOOL)isPureInt:(NSString *)string
    {
        　　NSScanner* scan = [NSScanner scannerWithString:string];
        　　int val;
        　　return [scan scanInt:&val] && [scan isAtEnd];
    }
    //判断是否为空
- (BOOL)stringIsEmpty{
    if([self isKindOfClass:[NSNull class]]){
        return YES;
    }
    NSString *text = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    if ([text length] == 0) {
        return YES;
    }
    return NO;
}
    //MD5加密
- (id)MD5{
    const char *cStr = [self UTF8String];
    unsigned char digest[16];
    unsigned int x=(int)strlen(cStr) ;
    CC_MD5( cStr, x, digest );
    // This is the md5 call
    NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
    
    for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
    [output appendFormat:@"%02x", digest[i]];
    
    return  output;
}
    
    //手机号码合法性判断
-(BOOL)validateMobile{
    NSString *MobileRegex = @"^0?(13[0-9]|15[0-9]|17[0-9]|18[0-9]|14[0-9])[0-9]{8}$";
    NSPredicate *phoneNum = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",MobileRegex];
    return [phoneNum evaluateWithObject:self];
}
    //身份证合法性判断最终版;
+ (BOOL)validateTruePeopleIDCode:(NSString *)identityCard {
    
    BOOL flag;
    if (identityCard.length <= 0)
    {
        flag = NO;
        return flag;
    }
    
    NSString *regex2 = @"^(^[1-9]\\d{7}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])\\d{3}$)|(^[1-9]\\d{5}[1-9]\\d{3}((0\\d)|(1[0-2]))(([0|1|2]\\d)|3[0-1])((\\d{4})|\\d{3}[Xx])$)$";
    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    flag = [identityCardPredicate evaluateWithObject:identityCard];
    
    
    //如果通过该验证，说明身份证格式正确，但准确性还需计算
    if(flag)
    {
        if(identityCard.length==18)
        {
            //将前17位加权因子保存在数组里
            NSArray * idCardWiArray = @[@"7", @"9", @"10", @"5", @"8", @"4", @"2", @"1", @"6", @"3", @"7", @"9", @"10", @"5", @"8", @"4", @"2"];
            
            //这是除以11后，可能产生的11位余数、验证码，也保存成数组
            NSArray * idCardYArray = @[@"1", @"0", @"10", @"9", @"8", @"7", @"6", @"5", @"4", @"3", @"2"];
            
            //用来保存前17位各自乖以加权因子后的总和
            
            NSInteger idCardWiSum = 0;
            for(int i = 0;i < 17;i++)
            {
                NSInteger subStrIndex = [[identityCard substringWithRange:NSMakeRange(i, 1)] integerValue];
                NSInteger idCardWiIndex = [[idCardWiArray objectAtIndex:i] integerValue];
                
                idCardWiSum+= subStrIndex * idCardWiIndex;
                
            }
            
            //计算出校验码所在数组的位置
            NSInteger idCardMod=idCardWiSum%11;
            
            //得到最后一位身份证号码
            NSString * idCardLast= [identityCard substringWithRange:NSMakeRange(17, 1)];
            
            //如果等于2，则说明校验码是10，身份证号码最后一位应该是X
            if(idCardMod==2)
            {
                if([idCardLast isEqualToString:@"X"]||[idCardLast isEqualToString:@"x"])
                {
                    return flag;
                }else
                {
                    flag =  NO;
                    return flag;
                }
            }else
            {
                //用计算出的验证码与最后一位身份证号码匹配，如果一致，说明通过，否则是无效的身份证号码
                if([idCardLast isEqualToString: [idCardYArray objectAtIndex:idCardMod]])
                {
                    return flag;
                }
                else
                {
                    flag =  NO;
                    return flag;
                }
            }
        }
        else
        {
            flag =  NO;
            return flag;
        }
    }
    else
    {
        return flag;
    }
    
    
    
}
    
    
    //身份证合法性判断
-(BOOL)validateIdentityCard{
    NSString *indetityCardRegex = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    NSPredicate *identityCard = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",indetityCardRegex];
    return [identityCard evaluateWithObject:self];
}
    //密码合法性判断
-(BOOL)validatePassword{
    NSString *passwordRegex = @"^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,16}$";
    NSPredicate *password = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",passwordRegex];
    return [password evaluateWithObject:self];
    
}
    //含有六位数字
-(BOOL)validatePhoneCode{
    NSString *codeRegex = @"^[0-9]{6}$";
    NSPredicate *phondCode = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",codeRegex];
    return [phondCode evaluateWithObject:self];
}
    
    //邮箱地址的正则表达式
- (BOOL)isValidateEmail{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:self];
}
- (BOOL)isValidateNumAndA{
    
    NSString *numCheck = @"[A-Z0-9a-z]";
    
    NSPredicate *numTest = [NSPredicate predicateWithFormat:@"SELF MATCHES%@",numCheck];
    
    return [numTest evaluateWithObject:self];
    
}
    
    //认证使用
- (NSString *)Base64EncodedStringFromString:(NSString *)string {
    NSData *data = [NSData dataWithBytes:[string UTF8String] length:[string lengthOfBytesUsingEncoding:NSUTF8StringEncoding]];
    NSUInteger length = [data length];
    NSMutableData *mutableData = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    
    uint8_t *input = (uint8_t *)[data bytes];
    uint8_t *output = (uint8_t *)[mutableData mutableBytes];
    
    for (NSUInteger i = 0; i < length; i += 3) {
        NSUInteger value = 0;
        for (NSUInteger j = i; j < (i + 3); j++) {
            value <<= 8;
            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }
        
        static uint8_t const kAFBase64EncodingTable[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
        
        NSUInteger idx = (i / 3) * 4;
        output[idx + 0] = kAFBase64EncodingTable[(value >> 18) & 0x3F];
        output[idx + 1] = kAFBase64EncodingTable[(value >> 12) & 0x3F];
        output[idx + 2] = (i + 1) < length ? kAFBase64EncodingTable[(value >> 6)  & 0x3F] : '=';
        output[idx + 3] = (i + 2) < length ? kAFBase64EncodingTable[(value >> 0)  & 0x3F] : '=';
    }
    
    return [[NSString alloc] initWithData:mutableData encoding:NSASCIIStringEncoding];
}
    
    //是否有中文
- (BOOL)validateChinese{
    NSString *chineseRegex = @"^[\u4e00-\u9fa5]*$";
    NSPredicate *chinese = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",chineseRegex];
    return [chinese evaluateWithObject:self];
}
    //判断数字
    /**
     *  『正则表达式；推荐使用，不用循环遍历，控制更灵活』判断字符串内容是否是有效数字
     *
     *  @param string 需要验证的字符串
     *
     *  @return 字符串内容是否是有效数字
     */
- (BOOL)validateNumberByRegExp {
    BOOL isValid = YES;
    NSUInteger len = self.length;
    if (len > 0) {
        NSString *numberRegex = @"^[0-9]*$";
        NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
        isValid = [numberPredicate evaluateWithObject:self];
    }
    return isValid;
}
//判断数字或小数点
/**
 *  『正则表达式；推荐使用，不用循环遍历，控制更灵活』判断字符串内容是否是有效数字
 *
 *  @param string 需要验证的字符串
 *
 *  @return 判断数字和小数点
 */
- (BOOL)validateNumberAndDotByRegExp {
    BOOL isValid = YES;
    NSUInteger len = self.length;
    if (len > 0) {
        NSString *numberRegex = @"^[0-9]+(.[0-9]{2})?$";
        NSPredicate *numberPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegex];
        isValid = [numberPredicate evaluateWithObject:self];
    }
    return isValid;
}
//护照验证
/**
 *  『正则表达式；推荐使用，不用循环遍历，控制更灵活』判断字符串内容是否是有效数字
 *
 *  @param string 需要验证的字符串
 *
 *  @return 判断护照验证
 */
- (BOOL)validatePassportNumberByRegExp {
    BOOL isValidA = NO;
    BOOL isValidB = NO;
    NSUInteger len = self.length;
    if (len > 0) {
        NSString *numberRegexA = @"^[a-zA-Z]{5,17}$";
        NSPredicate *numberPredicateA = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegexA];
        isValidA = [numberPredicateA evaluateWithObject:self];
        NSString *numberRegexB = @"^[a-zA-Z0-9]{5,17}$";
        NSPredicate *numberPredicateB = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", numberRegexB];
        isValidB = [numberPredicateB evaluateWithObject:self];
    }
    return isValidA||isValidB;
}

- (NSDate *)dateByAddingDays:(NSInteger)days {
    NSTimeInterval aTimeInterval = [NSDate timeIntervalSinceReferenceDate] + 86400 * days;
    NSDate *newDate = [NSDate dateWithTimeIntervalSinceReferenceDate:aTimeInterval];
    return newDate;
}
- (NSString *)trimming {
    NSString *neStr = [self stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    return neStr;
}
+ (NSString *)saveImage:(UIImage *)tempImage WithName:(NSString *)imageName
    {
        NSData* imageData = nil;
        
        //    if (UIImagePNGRepresentation(tempImage) == nil)
        //    {
        imageName = [imageName stringByAppendingString:@".jpg"];
        imageData = UIImageJPEGRepresentation(tempImage, 0.2);
        //    }else{
        //        imageName = [imageName stringByAppendingString:@".png"];
        //        imageData = UIImagePNGRepresentation(tempImage);
        //    }
        
        NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString* documentsDirectory = [paths objectAtIndex:0];
        
        NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:imageName];
        [imageData writeToFile:fullPathToFile atomically:NO];
        
        return fullPathToFile;
    }
    
    
+ (NSString *) boolToString:(BOOL)bol {
    NSString *string = @"";
    string = bol ? @"true" : @"false";
    return string;
}
+ (BOOL) StringToBool:(NSString *)bol {
    BOOL string = NO;
    string = [bol isEqualToString:@"1"] ? YES : NO;
    return string;
}
+ (NSString *) string:(NSString *)oneStr divide:(NSString *)twoString {
    
    NSString *res = @"";
    
    CGFloat one = [oneStr floatValue];
    CGFloat two = [twoString floatValue];
    if (two == 0) {
        res = @"%100";
    } else {
        
        res = [NSString stringWithFormat:@"%%%.2f",one/two];
        
    }
    return res;
}
    
    
+(NSString *)stringFromStatusId:(NSString *)statusId {
    NSString *res = @"";
    
    if ([statusId isEqualToString:@"ORDER_CREATED"]) {
        res = @"待付款";
    }
    if ([statusId isEqualToString:@"ORDER_PAYED"]) {
        res = @"待收货";
    }
    if ([statusId isEqualToString:@"ORDER_SENT"]) {
        res = @"待收货";
    }
    if ([statusId isEqualToString:@"ORDER_ACCEPT"]) {
        res = @"待评价";
    }
    if ([statusId isEqualToString:@"ORDER_CANCELLED"]) {
        res = @"取消订单";
    }
    return res;
}
    

- (NSString *)cutString:(NSRange )ran {
    NSString *res = @"";
    [self substringFromIndex:ran.location];
    return res;
}

+ (BOOL)isSxistAtPath:(NSString *)filePath{
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    NSString* fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filePath];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL isExist = [fileManager fileExistsAtPath:fullPathToFile];
    return isExist;
}

+ (NSString *)fullPathWithpath:(NSString *)filePath {
    NSString* fullPathToFile = @"";
    NSArray* paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString* documentsDirectory = [paths objectAtIndex:0];
    fullPathToFile = [documentsDirectory stringByAppendingPathComponent:filePath];
    return fullPathToFile;
}

- (NSString *)sexChangeToMF {
    NSString * sexStr = @"";
    sexStr = [self isEqualToString:@"男"] ? @"M" : @"F";
    return sexStr;
}

- (NSString *)mfChangeToChinaSex {
    NSString * sexStr = @"";
    sexStr = [self isEqualToString:@"M"] ? @"男" : @"女";
    return sexStr;
}


-(NSString *)toCapitalLetters:(NSString *)money {//首先转化成标准格式        “200.23”
    NSMutableString *tempStr=[[NSMutableString alloc] initWithString:[NSString stringWithFormat:@"%.2f",[money doubleValue]]];
    //位
    NSArray *carryArr1=@[@"元", @"拾", @"佰", @"仟", @"万", @"拾", @"佰", @"仟", @"亿", @"拾", @"佰", @"仟", @"兆", @"拾", @"佰", @"仟" ];
    NSArray *carryArr2=@[@"分",@"角"];
    //数字
    NSArray *numArr=@[@"零", @"壹", @"贰", @"叁", @"肆", @"伍", @"陆", @"柒", @"捌", @"玖"];
    
    NSArray *temarr = [tempStr componentsSeparatedByString:@"."];
    //小数点前的数值字符串
    NSString *firstStr=[NSString stringWithFormat:@"%@",temarr[0]];
    //小数点后的数值字符串
    NSString *secondStr=[NSString stringWithFormat:@"%@",temarr[1]];
    
    //是否拼接了“零”，做标记
    bool zero=NO;
    //拼接数据的可变字符串
    NSMutableString *endStr=[[NSMutableString alloc] init];
    
    /**
     *  首先遍历firstStr，从最高位往个位遍历    高位----->个位
     */
    
    for(int i=(int)firstStr.length;i>0;i--)
    {
        //取最高位数
        NSInteger MyData=[[firstStr substringWithRange:NSMakeRange(firstStr.length-i, 1)] integerValue];
        
        if ([numArr[MyData] isEqualToString:@"零"]) {
            
            if ([carryArr1[i-1] isEqualToString:@"万"]||[carryArr1[i-1] isEqualToString:@"亿"]||[carryArr1[i-1] isEqualToString:@"元"]||[carryArr1[i-1] isEqualToString:@"兆"]) {
                //去除有“零万”
                if (zero) {
                    endStr =[NSMutableString stringWithFormat:@"%@",[endStr substringToIndex:(endStr.length-1)]];
                    [endStr appendString:carryArr1[i-1]];
                    zero=NO;
                }else{
                    [endStr appendString:carryArr1[i-1]];
                    zero=NO;
                }
                
                //去除有“亿万”、"兆万"的情况
                if ([carryArr1[i-1] isEqualToString:@"万"]) {
                    if ([[endStr substringWithRange:NSMakeRange(endStr.length-2, 1)] isEqualToString:@"亿"]) {
                        endStr =[NSMutableString stringWithFormat:@"%@",[endStr substringToIndex:endStr.length-1]];
                    }
                    
                    if ([[endStr substringWithRange:NSMakeRange(endStr.length-2, 1)] isEqualToString:@"兆"]) {
                        endStr =[NSMutableString stringWithFormat:@"%@",[endStr substringToIndex:endStr.length-1]];
                    }
                    
                }
                //去除“兆亿”
                if ([carryArr1[i-1] isEqualToString:@"亿"]) {
                    if ([[endStr substringWithRange:NSMakeRange(endStr.length-2, 1)] isEqualToString:@"兆"]) {
                        endStr =[NSMutableString stringWithFormat:@"%@",[endStr substringToIndex:endStr.length-1]];
                    }
                }
                
                
            }else{
                if (!zero) {
                    [endStr appendString:numArr[MyData]];
                    zero=YES;
                }
                
            }
            
        }else{
            //拼接数字
            [endStr appendString:numArr[MyData]];
            //拼接位
            [endStr appendString:carryArr1[i-1]];
            //不为“零”
            zero=NO;
        }
    }
    
    /**
     *  再遍历secondStr    角位----->分位
     */
    
    if ([secondStr isEqualToString:@"00"]) {
        [endStr appendString:@"整"];
    }else{
        for(int i=(int)secondStr.length;i>0;i--)
        {
            //取最高位数
            NSInteger MyData=[[secondStr substringWithRange:NSMakeRange(secondStr.length-i, 1)] integerValue];
            
            [endStr appendString:numArr[MyData]];
            [endStr appendString:carryArr2[i-1]];
        }
    }
    
    return endStr;
}

+ (NSString *)firstCharactor:(NSString *)aString
{
    if (![aString validateChinese]) {
        return aString;
    }
    //转成了可变字符串
    NSMutableString *str = [NSMutableString stringWithString:aString];
    //先转换为带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformMandarinLatin,NO);
    //再转换为不带声调的拼音
    CFStringTransform((CFMutableStringRef)str,NULL, kCFStringTransformStripDiacritics,NO);
    //转化为大写拼音
    NSString *pinYin = [str capitalizedString];
    //获取并返回首字母
    return [pinYin substringToIndex:1];
}

/**
 * 计算两日期之间时间之差
 * date1<date2
 */
+ (long) compareDate1:(NSDate *)date1 withDate2:(NSDate *)date2 type:(int)type
{
    NSTimeInterval  timeInterval = [date1 timeIntervalSinceDate:date2];
    timeInterval = -timeInterval;
    long result;
    switch (type) {
        case 1:
            result = (long)timeInterval;    //秒
            break;
        case 2:
            result = (long)timeInterval/60;    //分
            break;
        case 3:
            result = (long)timeInterval/60/60;    //时
            break;
        case 4:
            result = (long)timeInterval/60/60/24;    //天
            break;
        case 5:
            result = (long)timeInterval/60/60/24/30;    //月
            break;
        case 6:
            result = (long)timeInterval/60/60/24/365;    //年
            break;
        default:
            break;
    }
    return result;
}
- (NSDate *)stringToDate {
    NSDate* inputDate = nil;
    NSString* string = self;
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init] ;
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"] ];
    [inputFormatter setDateFormat:@"yyyyMMddHHmmss"];
   inputDate = [inputFormatter dateFromString:string];
    return inputDate;
}


+ (NSString *)dataStringFromDate:(NSInteger )date {
    NSString* inputDate = nil;
//    inputDate = [[NSDate dateWithTimeIntervalSince1970:(date/1000)] stringWithFormat:@"MM-dd HH:mm"];
    return inputDate;
}
//字符串转日期
+ (NSDate *)getDateFromString:(NSString *)string
{
    if ([string rangeOfString:@"."].length>0) {
        string=[string substringToIndex:[string rangeOfString:@"."].location];
    }
    NSDateFormatter* dateFormat = [[NSDateFormatter alloc] init];//实例化一个NSDateFormatter对象
    if ([string rangeOfString:@" "].length>0) {
        [dateFormat setDateFormat:@"yyyy-MM-dd HH:mm:ss"];//设定时间格式,这里可以设置成自己需要的格式
    }else{
        [dateFormat setDateFormat:@"yyyy-MM-dd"];//设定时间格式,这里可以设置成自己需要的格式
    }
    if ([string rangeOfString:@"."].length>0) {
        string=[string substringToIndex:[string rangeOfString:@"."].location];
    }
    NSDate *date =[dateFormat dateFromString:string];
    return  date;
}


+(NSString *) jiexi:(NSString *)CS webaddress:(NSString *)webaddress
{
    NSError *error;
    NSString *regTags=[[NSString alloc] initWithFormat:@"(^|&|\\?)+%@=+([^&]*)(&|$)",CS];
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regTags
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    
    // 执行匹配的过程
    // NSString *webaddress=@"http://www.baidu.com/dd/adb.htm?adc=e12&xx=lkw&dalsjd=12";
    NSArray *matches = [regex matchesInString:webaddress
                                      options:0
                                        range:NSMakeRange(0, [webaddress length])];
    for (NSTextCheckingResult *match in matches) {
        //NSRange matchRange = [match range];
        //NSString *tagString = [webaddress substringWithRange:matchRange];  // 整个匹配串
        //        NSRange r1 = [match rangeAtIndex:1];
        //        if (!NSEqualRanges(r1, NSMakeRange(NSNotFound, 0))) {    // 由时分组1可能没有找到相应的匹配，用这种办法来判断
        //            //NSString *tagName = [webaddress substringWithRange:r1];  // 分组1所对应的串
        //            return @"";
        //        }
        
        NSString *tagValue = [webaddress substringWithRange:[match rangeAtIndex:2]];  // 分组2所对应的串
        //    NSLog(@"分组2所对应的串:%@\n",tagValue);
        return tagValue;
    }
    return @"";
}
- (NSString *)MD5Hash {
    if(self.length == 0) {
        return nil;
    }
    
    const char *cStr = [self UTF8String];
    unsigned char result[16];
    CC_MD5(cStr, (CC_LONG)strlen(cStr), result);
    
    return [NSString stringWithFormat:@"%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X%02X",
            result[0], result[1], result[2], result[3], result[4], result[5], result[6], result[7],
            result[8], result[9], result[10], result[11],result[12], result[13], result[14], result[15]];
}



//MARK::--  仿QQ空间时间显示
- (NSString *)QQTimeformat{
    NSDateFormatter *inputFormatter= [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] ];
    [inputFormatter setDateFormat:@"yyyy年MM月dd日 HH时mm分ss秒"];
    NSDate*inputDate = [inputFormatter dateFromString:self];
    //NSLog(@"startDate= %@", inputDate);
    
    NSDateFormatter *outputFormatter= [[NSDateFormatter alloc] init];
    [outputFormatter setLocale:[NSLocale currentLocale]];
    [outputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    //get date str
    NSString *str= [outputFormatter stringFromDate:inputDate];
    //str to nsdate
    NSDate *strDate = [outputFormatter dateFromString:str];
    //修正8小时的差时
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: strDate];
    NSDate *endDate = [strDate  dateByAddingTimeInterval: interval];
    //NSLog(@"endDate:%@",endDate);
    NSString *lastTime = [self compareDate:endDate];
    NSLog(@"lastTime = %@",lastTime);
    return lastTime;
}

-(NSString *)compareDate:(NSDate *)date{
    
    NSTimeInterval secondsPerDay = 24 * 60 * 60;
    
    //修正8小时之差
    NSDate *date1 = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date1];
    NSDate *localeDate = [date1  dateByAddingTimeInterval: interval];
    
    //NSLog(@"nowdate=%@\nolddate = %@",localeDate,date);
    NSDate *today = localeDate;
    NSDate *yesterday,*beforeOfYesterday;
    //今年
    NSString *toYears;
    
    toYears = [[today description] substringToIndex:4];
    
    yesterday = [today dateByAddingTimeInterval: -secondsPerDay];
    beforeOfYesterday = [yesterday dateByAddingTimeInterval: -secondsPerDay];
    
    // 10 first characters of description is the calendar date:
    NSString *todayString = [[today description] substringToIndex:10];
    NSString *yesterdayString = [[yesterday description] substringToIndex:10];
    NSString *beforeOfYesterdayString = [[beforeOfYesterday description] substringToIndex:10];
    
    NSString *dateString = [[date description] substringToIndex:10];
    NSString *dateYears = [[date description] substringToIndex:4];
    
    NSString *dateContent;
    if ([dateYears isEqualToString:toYears]) {//同一年
        //今 昨 前天的时间
        NSString *time = [[date description] substringWithRange:(NSRange){11,5}];
        //其他时间
        NSString *time2 = [[date description] substringWithRange:(NSRange){5,11}];
        if ([dateString isEqualToString:todayString]){
            dateContent = PXY_STR(PXYLocal(@"messagelist_timeToday_tittle_msg"),time);
//            dateContent = [NSString stringWithFormat:@"今天 %@",time];
            return dateContent;
        } else if ([dateString isEqualToString:yesterdayString]){
             dateContent = PXY_STR(PXYLocal(@"messagelist_timeYesterday_tittle_msg"),time);
//            dateContent = [NSString stringWithFormat:@"昨天 %@",time];
            return dateContent;
        }else if ([dateString isEqualToString:beforeOfYesterdayString]){
             dateContent = PXY_STR(PXYLocal(@"messagelist_timeAnteayer_tittle_msg"),time);
//            dateContent = [NSString stringWithFormat:@"前天 %@",time];
            return dateContent;
        }else{
            return time2;
        }
    }else{
        return dateString;
    }
}

- (NSString *)weekString {
    NSString *weekStr = nil;
    
    if ([self isEqualToString:@"1"]) {
        weekStr = PXYLocal(@"week_Monday_message");
    }
    else if ([self isEqualToString:@"2"]) {
        weekStr = PXYLocal(@"week_Tuesday_message");
    }
    else if ([self isEqualToString:@"3"]) {
        weekStr = PXYLocal(@"week_Wednesday_message");
    }
    else if ([self isEqualToString:@"4"]) {
        weekStr = PXYLocal(@"week_Thursday_message");
    }
    else if ([self isEqualToString:@"5"]) {
        weekStr = PXYLocal(@"week_Friday_message");
    }
    else if ([self isEqualToString:@"6"]) {
        weekStr = PXYLocal(@"week_Saturday_message");
    }
    else if([self isEqualToString:@"7"]) {
        weekStr = PXYLocal(@"week_Sunday_message");
    }
    
    return weekStr;
   
}



@end
